<?php
// +----------------------------------------------------------------------
// | i友街 [ 新生代贵州网购社区 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2014 http://www.iyo9.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: i友街 <iyo9@iyo9.com> <http://www.iyo9.com>
// +----------------------------------------------------------------------
// 

/**
 * 中国省市区三级联动插件
 * @author i友街
 */

namespace Addons\InsertXiami\Controller;
use Home\Controller\AddonsController;

class XiamiController extends AddonsController{
   public function searchMusic(){
       $aPage = I('post.page',1,'intval');
       $aKey = I('post.key','','text');
       if(empty($aKey)){
           $return['status']=-1;
           $this->ajaxReturn($return);
       }
       $aKey = urlencode($aKey);
       $arr = $this->getMusic($aKey,$aPage);
       $next = $this->getMusic($aKey,$aPage+1);
       if(empty($arr)){
           $return['status']=0;
       }else{
           $return =  array('status'=>1,'data'=>$arr,'next'=>count($next));
       }
       $this->ajaxReturn($return);
   }


    private function getMusic($key,$page){
        $result = S('xiami_search_'.$key.'_'.$page);
        if(empty($result)){
            $url=   'http://www.xiami.com/web/search-songs?key='.$key.'&page='.$page;
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_TIMEOUT, 5);
            curl_setopt($ch, CURLOPT_USERAGENT, '');
            curl_setopt($ch, CURLOPT_REFERER,'b');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $content = curl_exec($ch);
            curl_close($ch);
            $result = json_decode($content,true);
            S('xiami_search_'.$key.'_'.$page,$result,60*60);
        }
        return $result;

    }


}